#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <cstdlib>
#include <string.h>
#include <memory>
#include "nocopy.hpp"
#include "InetAddr.hpp"
#include "Common.hpp"
#include "Log.hpp"

using namespace LogModule;

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        return 1;
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    // 1.还是创建socket
    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "socket error...";
        return 2;
    }
    LOG(LogLevel::DEBUG) << "sockfd success: " << sockfd;
    // 2.clent 也要进行bind，但是不要跟server一样显示的进行bind，因为服务器的port是众所周知的，而client的port可能会非常多
    // 导致端口号冲突，bind的操作OS会随机给我们分配端口号

    // 3.填充server信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_addr.s_addr = inet_addr(server_ip.c_str()); // ip地址是点分十进制转换为网络序列的32为整数
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);

    while (true)
    {
        std::string in;
        std::cout << "please enter# ";
        std::getline(std::cin, in);
        // std::cin>>in;
        //  std::cout<< 1 <<std::endl;
        int n = sendto(sockfd, in.c_str(), in.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "sendto failed";
            continue;
        }

        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t peer_len = sizeof(peer);
        int m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &peer_len);

        if (m > 0)
        {
            buffer[m] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}
